/**
 * Created by zhaojm on 15/4/5.
 */
game.GameOverLayer = cc.Layer.extend({

    _score : null,
    _world:null,
    _heroPos : null,
    ctor:function(data, world, pos){
        this._super();
        var self = this;
        this._world = world;
        this._heroPos = pos;


        //if(game._Config.language == game._Enum.language.en) {
        //    window['Ads']['fullViewAds']();
        //}


        if(game._Config.language == game._Enum.language.cn){
            var text1 = cc.LabelTTF.create('最高纪录:', 'Arial', 18);
        }else{
            var text1 = cc.LabelTTF.create('HIGHSCORE:', 'Arial', 18);
        }
        text1.setColor(new cc.Color(74, 186, 214));
        text1.setPosition(cc.p(cc.winSize.width * 0.6, cc.winSize.height * 0.27));
        text1.setAnchorPoint(cc.p(1, 0.5));
        this.addChild(text1);

        if(game._Config.language == game._Enum.language.cn){
            var text2 = cc.LabelTTF.create('当前得分:', 'Arial', 18);
        }else{
            var text2 = cc.LabelTTF.create('GAMES PLAYED:', 'Arial', 18);
        }
        text2.setColor(new cc.Color(74, 186, 214));
        text2.setPosition(cc.p(cc.winSize.width * 0.6, cc.winSize.height * 0.2));
        text2.setAnchorPoint(cc.p(1, 0.5));
        this.addChild(text2);

        this._score = cc.LabelTTF.create('', 'Arial', 18);
        this._score.setColor(new cc.Color(74, 186, 214));
        this._score.setPosition(cc.p(cc.winSize.width * 0.7, cc.winSize.height * 0.2));
        this.addChild(this._score);
        //this.numScore.setAnchorPoint(cc.p(0, 0.5));

// 最高纪录
        this.highScore = cc.LabelTTF.create('', 'Arial', 18);
        this.highScore.setColor(new cc.Color(74, 186, 214));
        this.highScore.setPosition(cc.p(cc.winSize.width * 0.7, cc.winSize.height * 0.27));
        this.addChild(this.highScore);
        //this.distance.setAnchorPoint(cc.p(0, 0.5));


        var name = 'ball_data';
        var temp = cc.sys.localStorage.getItem(name);
        //将字符串转化为json
        temp = JSON.parse(temp);

        cc.log('temp==', temp, 'data=', data);


        if(temp == null || temp == "" || temp == 'undefined'){
            cc.sys.localStorage.setItem(name, JSON.stringify(data));
            //level.setSpriteFrame(cc.spriteFrameCache.getSpriteFrame('level0.png'));
            // TODO 第一次
            cc.log('first time...');
            this._score.setString(data.score.toFixed(0));
            this.highScore.setString(data.score.toFixed(0));

        }else{
            cc.log('not first time');


            if(temp.score < data.score) {
                cc.sys.localStorage.setItem(name, JSON.stringify(data));
                // TODO 覆盖 最高纪录
                cc.log('big score num ');
                this._score.setString(data.score.toFixed(0));
                this.highScore.setString(data.score.toFixed(0));
                // 最高
                //level.setSpriteFrame(cc.spriteFrameCache.getSpriteFrame('level0.png'));

            }else{
                cc.log('再接再厉。。');
                //level.setSpriteFrame(cc.spriteFrameCache.getSpriteFrame('level1.png'));
                this._score.setString(data.score.toFixed(0));

                if(temp.score){
                    this.highScore.setString(temp.score.toFixed(0));
                }else{
                    this.highScore.setString(data.score.toFixed(0));
                }

            }

        }


        this.gameOver();

    },

    gameOver:function(){
        cc.log('game layer game over');




        var pos = this._heroPos;

        this.createWall();


        this.createGameOverRole(pos, res.restart_png, function(){
            cc.log('restart...');
            cc.director.runScene(new game.GameScene());
        }.bind(this));
        this.createGameOverRole(pos, res.setting_png, function(){
            cc.log('setting');
        }.bind(this));
        this.createGameOverRole(pos, res.rankings_png, function(){
            cc.log('rankings');
            window.location.href="http://mingz.me";
        }.bind(this));
        this.createGameOverRole(pos, res.gameover_1_png, function(){
            cc.log('gameover 1');
            window.location.href="http://mingz.me";
        }.bind(this));
        this.createGameOverRole(pos, res.gameover_3_png, function(){
            cc.log('cup...');
            window.location.href="http://mingz.me";
        }.bind(this));
        this.createGameOverRole(pos, res.gameover_4_png, function(){
            cc.log('share...');
            cc.log('on share...');
            if (game._Config.language == game._Enum.language.cn) {
                //this.addChild(new game.ShareLayer(), 2);
                this.addShare();
            }else{

                // TODO  facebook share
                //
                //var map = {
                //    "dialog": "shareLink",
                //    "name": "Cocos2d-JS web site",
                //    "caption": "Cocos2d-JS caption",
                //    "description":"Cocos2d-JS description",
                //    //"to": "100008180737293,100006738453912",
                //    //"picture": "http://files.cocos2d-x.org/images/orgsite/logo.png",
                //    "link": "http://www.cocos2d-x.org"
                //};
                //
                //if(window.facebook.canPresentDialog(map)){
                //    window.facebook.dialog(map,function(errorCode,msg){
                //        cc.log(JSON.stringify(msg));
                //    });
                //}else{
                //    map["dialog"] = "feedDialog";
                //    window.facebook.dialog(map,function(errorCode,msg){
                //        cc.log(JSON.stringify(msg));
                //    });
                //}


            }

        }.bind(this));
    },

    createGameOverRole:function(p, frame, callback){
        var b2BodyDef = Box2D.Dynamics.b2BodyDef
            , b2Body = Box2D.Dynamics.b2Body
            , b2FixtureDef = Box2D.Dynamics.b2FixtureDef
            , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
            , b2CircleShape = Box2D.Collision.Shapes.b2CircleShape
            , b2Vec2 = Box2D.Common.Math.b2Vec2;


        var sprite = new cc.Sprite(frame);
        sprite.x = p.x;
        sprite.y = p.y;
        this.addChild(sprite);

        var listener1 = cc.EventListener.create({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            swallowTouches: true,
            onTouchBegan: function (touch, event) {
                var target = event.getCurrentTarget();

                var locationInNode = target.convertToNodeSpace(touch.getLocation());
                var s = target.getContentSize();
                var rect = cc.rect(0, 0, s.width, s.height);

                if (cc.rectContainsPoint(rect, locationInNode)) {
                    //cc.log("sprite began... x = " + locationInNode.x + ", y = " + locationInNode.y);
                    //target.opacity = 180;

                    callback();

                    return true;
                }
                return false;
            },

        });

        cc.eventManager.addListener(listener1, sprite);

        var bodyDef = new b2BodyDef();
        bodyDef.type = b2Body.b2_dynamicBody;
        bodyDef.position.Set(p.x / PTM_RATIO, p.y / PTM_RATIO);
        bodyDef.userData = sprite;

        var circle =  new b2CircleShape();
        circle.SetRadius(sprite.getContentSize().height / 2 / PTM_RATIO);   // 半径

        var fixtureDef = new b2FixtureDef();
        fixtureDef.shape = circle;
        fixtureDef.density = 1.0;   // 密度
        fixtureDef.friction = 0.0;  // 摩擦系数
        fixtureDef.restitution = 0.0;   // 弹性


        //cc.log('bodydef=', bodyDef);
        var body = this._world.CreateBody(bodyDef);
        //cc.log('body==', body);
        body.CreateFixture(fixtureDef);
    },


    createWall:function(){
        var winSize = cc.winSize;

        var b2BodyDef = Box2D.Dynamics.b2BodyDef
            , b2Body = Box2D.Dynamics.b2Body
            , b2FixtureDef = Box2D.Dynamics.b2FixtureDef
            , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
            , b2CircleShape = Box2D.Collision.Shapes.b2CircleShape
            , b2Vec2 = Box2D.Common.Math.b2Vec2;

        var fixDef = new b2FixtureDef;
        fixDef.density = 1.0;
        fixDef.friction = 0.0;  // 摩擦
        fixDef.restitution = 0.0;   // 弹性
        fixDef.shape = new b2PolygonShape();
        fixDef.shape.SetAsBox(1 / PTM_RATIO, winSize.height / 2 / PTM_RATIO);

        var bodyDef = new b2BodyDef();
        bodyDef.type = b2Body.b2_staticBody;

        // left
        bodyDef.position.Set(0 / PTM_RATIO, winSize.height / 2 / PTM_RATIO);
        this._world.CreateBody(bodyDef).CreateFixture(fixDef);
        // right
        bodyDef.position.Set(winSize.width / PTM_RATIO, winSize.height / 2 / PTM_RATIO);
        this._world.CreateBody(bodyDef).CreateFixture(fixDef);
    },

    addShare:function(){
        this.addChild(new game.ShareLayer());
    },


});